package com.hlj.ncp.warehouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlj.ncp.warehouse.entity.ColdStorageMonitor;
import com.hlj.ncp.warehouse.entity.ColdStorageThreshold;
import com.hlj.ncp.warehouse.mapper.ColdStorageMonitorMapper;
import com.hlj.ncp.warehouse.service.IColdStorageMonitorService;
import com.hlj.ncp.warehouse.service.IColdStorageThresholdService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 冷库湿温度监控 服务层实现
 */
@Service
public class ColdStorageMonitorServiceImpl extends ServiceImpl<ColdStorageMonitorMapper, ColdStorageMonitor> implements IColdStorageMonitorService {

    @Autowired
    private IColdStorageThresholdService coldStorageThresholdService;

    /**
     * 查询冷库湿温度监控列表
     * 
     * @param coldStorageMonitor 冷库湿温度监控信息
     * @return 冷库湿温度监控
     */
    @Override
    public List<ColdStorageMonitor> selectColdStorageMonitorList(ColdStorageMonitor coldStorageMonitor) {
        LambdaQueryWrapper<ColdStorageMonitor> queryWrapper = new LambdaQueryWrapper<>();
        
        // 构建查询条件
        if (coldStorageMonitor != null) {
            // 按仓库ID查询
            if (coldStorageMonitor.getWarehouseId() != null) {
                queryWrapper.eq(ColdStorageMonitor::getWarehouseId, coldStorageMonitor.getWarehouseId());
            }
            
            // 按仓库名称查询
            if (StringUtils.isNotBlank(coldStorageMonitor.getWarehouseName())) {
                queryWrapper.like(ColdStorageMonitor::getWarehouseName, coldStorageMonitor.getWarehouseName());
            }
            
            // 按冷库区域查询
            if (StringUtils.isNotBlank(coldStorageMonitor.getStorageArea())) {
                queryWrapper.eq(ColdStorageMonitor::getStorageArea, coldStorageMonitor.getStorageArea());
            }
            
            // 按设备ID查询
            if (StringUtils.isNotBlank(coldStorageMonitor.getDeviceId())) {
                queryWrapper.eq(ColdStorageMonitor::getDeviceId, coldStorageMonitor.getDeviceId());
            }
            
            // 按状态查询
            if (StringUtils.isNotBlank(coldStorageMonitor.getStatus())) {
                queryWrapper.eq(ColdStorageMonitor::getStatus, coldStorageMonitor.getStatus());
            }
            
            // 按处理状态查询
            if (StringUtils.isNotBlank(coldStorageMonitor.getProcessStatus())) {
                queryWrapper.eq(ColdStorageMonitor::getProcessStatus, coldStorageMonitor.getProcessStatus());
            }
        }
        
        // 默认按记录时间降序排序
        queryWrapper.orderByDesc(ColdStorageMonitor::getRecordTime);
        
        return this.list(queryWrapper);
    }

    /**
     * 查询冷库湿温度监控详细信息
     * 
     * @param monitorId 监控ID
     * @return 冷库湿温度监控信息
     */
    @Override
    public ColdStorageMonitor selectColdStorageMonitorById(Long monitorId) {
        return this.getById(monitorId);
    }

    /**
     * 新增冷库湿温度监控
     * 
     * @param coldStorageMonitor 冷库湿温度监控信息
     * @return 结果
     */
    @Override
    public int insertColdStorageMonitor(ColdStorageMonitor coldStorageMonitor) {
        // 设置创建时间
        coldStorageMonitor.setCreateTime(LocalDateTime.now());
        
        // 如果没有设置记录时间，则使用当前时间
        if (coldStorageMonitor.getRecordTime() == null) {
            coldStorageMonitor.setRecordTime(LocalDateTime.now());
        }
        
        // 检查温湿度是否超出阈值，设置状态和告警信息
        checkThresholdAndSetStatus(coldStorageMonitor);
        
        // 如果没有设置处理状态，默认为未处理
        if (StringUtils.isBlank(coldStorageMonitor.getProcessStatus())) {
            coldStorageMonitor.setProcessStatus("0");
        }
        
        // 如果状态不是正常，则发送告警通知
        if (!"0".equals(coldStorageMonitor.getStatus())) {
            sendAlarmNotification(coldStorageMonitor);
        }
        
        return this.save(coldStorageMonitor) ? 1 : 0;
    }

    /**
     * 修改冷库湿温度监控
     * 
     * @param coldStorageMonitor 冷库湿温度监控信息
     * @return 结果
     */
    @Override
    public int updateColdStorageMonitor(ColdStorageMonitor coldStorageMonitor) {
        // 设置更新时间
        coldStorageMonitor.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(coldStorageMonitor) ? 1 : 0;
    }

    /**
     * 批量删除冷库湿温度监控
     * 
     * @param monitorIds 需要删除的监控ID
     * @return 结果
     */
    @Override
    public int deleteColdStorageMonitorByIds(Long[] monitorIds) {
        return this.removeByIds(Arrays.asList(monitorIds)) ? monitorIds.length : 0;
    }

    /**
     * 删除冷库湿温度监控信息
     * 
     * @param monitorId 监控ID
     * @return 结果
     */
    @Override
    public int deleteColdStorageMonitorById(Long monitorId) {
        return this.removeById(monitorId) ? 1 : 0;
    }
    
    /**
     * 处理冷库湿温度告警
     * 
     * @param coldStorageMonitor 冷库湿温度监控信息
     * @return 结果
     */
    @Override
    public int processColdStorageMonitorAlarm(ColdStorageMonitor coldStorageMonitor) {
        // 设置处理时间
        coldStorageMonitor.setProcessTime(LocalDateTime.now());
        
        // 设置处理状态为已处理
        coldStorageMonitor.setProcessStatus("1");
        
        return this.updateById(coldStorageMonitor) ? 1 : 0;
    }
    
    /**
     * 查询最新的监控数据
     * 
     * @param warehouseId 仓库ID
     * @return 监控数据列表
     */
    @Override
    public List<ColdStorageMonitor> selectLatestMonitorData(Long warehouseId) {
        return baseMapper.selectLatestMonitorData(warehouseId);
    }
    
    /**
     * 统计各状态的监控数据
     * 
     * @param warehouseId 仓库ID
     * @return 统计结果
     */
    @Override
    public List<Map<String, Object>> selectMonitorStats(Long warehouseId) {
        return baseMapper.selectMonitorStats(warehouseId);
    }
    
    /**
     * 检查温湿度是否超出阈值，设置状态和告警信息
     * 
     * @param coldStorageMonitor 冷库湿温度监控信息
     */
    private void checkThresholdAndSetStatus(ColdStorageMonitor coldStorageMonitor) {
        // 查询该仓库区域的阈值设置
        ColdStorageThreshold threshold = coldStorageThresholdService.selectThresholdByWarehouseAndArea(
                coldStorageMonitor.getWarehouseId(), coldStorageMonitor.getStorageArea());
        
        // 如果没有设置阈值，则默认为正常状态
        if (threshold == null) {
            coldStorageMonitor.setStatus("0");
            return;
        }
        
        boolean temperatureAbnormal = false;
        boolean humidityAbnormal = false;
        StringBuilder alarmInfo = new StringBuilder();
        
        // 检查温度是否超出阈值
        if (coldStorageMonitor.getTemperature() != null) {
            if (threshold.getMinTemperature() != null && 
                    coldStorageMonitor.getTemperature().compareTo(threshold.getMinTemperature()) < 0) {
                temperatureAbnormal = true;
                alarmInfo.append("温度低于最低阈值(").append(threshold.getMinTemperature()).append("°C); ");
            } else if (threshold.getMaxTemperature() != null && 
                    coldStorageMonitor.getTemperature().compareTo(threshold.getMaxTemperature()) > 0) {
                temperatureAbnormal = true;
                alarmInfo.append("温度高于最高阈值(").append(threshold.getMaxTemperature()).append("°C); ");
            }
        }
        
        // 检查湿度是否超出阈值
        if (coldStorageMonitor.getHumidity() != null) {
            if (threshold.getMinHumidity() != null && 
                    coldStorageMonitor.getHumidity().compareTo(threshold.getMinHumidity()) < 0) {
                humidityAbnormal = true;
                alarmInfo.append("湿度低于最低阈值(").append(threshold.getMinHumidity()).append("%); ");
            } else if (threshold.getMaxHumidity() != null && 
                    coldStorageMonitor.getHumidity().compareTo(threshold.getMaxHumidity()) > 0) {
                humidityAbnormal = true;
                alarmInfo.append("湿度高于最高阈值(").append(threshold.getMaxHumidity()).append("%); ");
            }
        }
        
        // 设置状态和告警信息
        if (temperatureAbnormal && humidityAbnormal) {
            coldStorageMonitor.setStatus("3"); // 温湿度均异常
        } else if (temperatureAbnormal) {
            coldStorageMonitor.setStatus("1"); // 温度异常
        } else if (humidityAbnormal) {
            coldStorageMonitor.setStatus("2"); // 湿度异常
        } else {
            coldStorageMonitor.setStatus("0"); // 正常
        }
        
        if (alarmInfo.length() > 0) {
            coldStorageMonitor.setAlarmInfo(alarmInfo.toString());
        }
    }
    
    /**
     * 发送告警通知
     * 
     * @param coldStorageMonitor 冷库湿温度监控信息
     */
    private void sendAlarmNotification(ColdStorageMonitor coldStorageMonitor) {
        // 查询该仓库区域的阈值设置
        ColdStorageThreshold threshold = coldStorageThresholdService.selectThresholdByWarehouseAndArea(
                coldStorageMonitor.getWarehouseId(), coldStorageMonitor.getStorageArea());
        
        // 如果没有设置阈值或未启用通知，则不发送通知
        if (threshold == null || !"1".equals(threshold.getNotifyEnabled())) {
            return;
        }
        
        // TODO: 根据通知方式发送告警通知，这里可以集成短信、邮件、系统通知等
        // 示例：可以调用消息队列或通知服务发送告警
        
        // 记录日志
        System.out.println("发送告警通知：" + coldStorageMonitor.getWarehouseName() + 
                " - " + coldStorageMonitor.getStorageArea() + 
                " - " + coldStorageMonitor.getAlarmInfo());
    }

    /**
     * 查询指定时间范围内的监控数据
     * 
     * @param warehouseId 仓库ID
     * @param storageArea 冷库区域
     * @param deviceId 设备ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 监控数据列表
     */
    @Override
    public List<ColdStorageMonitor> selectHistoryData(Long warehouseId, String storageArea, String deviceId, 
                                                     LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.selectHistoryData(warehouseId, storageArea, deviceId, startTime, endTime);
    }
    
    /**
     * 查询温湿度趋势数据（按小时聚合）
     * 
     * @param warehouseId 仓库ID
     * @param storageArea 冷库区域
     * @param deviceId 设备ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 趋势数据列表
     */
    @Override
    public List<Map<String, Object>> selectTrendDataByHour(Long warehouseId, String storageArea, String deviceId, 
                                                          LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.selectTrendDataByHour(warehouseId, storageArea, deviceId, startTime, endTime);
    }
    
    /**
     * 查询温湿度趋势数据（按天聚合）
     * 
     * @param warehouseId 仓库ID
     * @param storageArea 冷库区域
     * @param deviceId 设备ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 趋势数据列表
     */
    @Override
    public List<Map<String, Object>> selectTrendDataByDay(Long warehouseId, String storageArea, String deviceId, 
                                                         LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.selectTrendDataByDay(warehouseId, storageArea, deviceId, startTime, endTime);
    }
} 